#!/bin/bash

##################################################################
## you need to sudo su (as root) before you can run this script ##
##################################################################

## the script install every under /root/pool

## lean up if any old setting
package="ml-svc.tar.gz"
if [ -f /root/ml-svc/$package ]; then
    rm -f /root/ml-svc/$package
fi

if [ -d /root/ml-svc/pool ]; then
    rm -rf /root/ml-svc/pool
fi

## remove old service
if [ -f /etc/systemd/system/ml-svc.service ]; then
    systemctl stop ml-svc.service
    systemctl disable ml-svc.service
    rm -f /etc/systemd/system/ml-svc.service
fi


## create the directory
if [ ! -d /root/ml-svc ]; then
    mkdir -p /root/ml-svc
fi

cd /root/ml-svc

## download the sw
wget https://gitee.com/changwei/minerlab/raw/master/v0.3/$package 
if [ $? -ne 0 ]; then
    echo "Failed to download $package"
    exit 1
fi

tar -zxvf $package
if [ $? -ne 0 ]; then
    echo "Failed to extract $package"
    exit 1
fi


## create a systemd service
cat << EOF > /etc/systemd/system/ml-svc.service
[Unit]
Description=ml-svc
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service


[Service]
User=root
WorkingDirectory=/root/ml-svc
ExecStart=/bin/bash -c '/root/ml-svc/ml-svc-linux'
Restart=always
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

rm -f ml-svc.tar.gz

systemctl enable ml-svc.service
echo "ml-svc service installed successfully."
systemctl start ml-svc.service

echo --------------------------------------------------------------
echo "ml-svc service installed, and started successfully."   
echo
